package com.jiantong.web.open.app.work;

import com.jiantong.common.util.UserUtil;
import com.jiantong.user.ext.LoginUser;
import com.jiantong.work.dto.SupervisionRecordsDto;
import com.jiantong.work.model.SupervisionRecords;
import com.jiantong.work.service.SupervisionRecordsReadService;
import com.jiantong.work.service.SupervisionRecordsWriteService;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import io.terminus.pampas.openplatform.annotations.OpenBean;
import io.terminus.pampas.openplatform.annotations.OpenMethod;
import io.terminus.pampas.openplatform.exceptions.OPClientException;
import io.terminus.pampas.openplatform.exceptions.OPServerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 督查轨迹 --政府端
 * Created by mz03 on 2017/3/24.
 * @author :zyp
 */
@Slf4j
@OpenBean
public class SupervisionRecordsApis {
    @RpcConsumer
    private SupervisionRecordsReadService supervisionRecordsReadService;

    @RpcConsumer
    private SupervisionRecordsWriteService supervisionRecordsWriteService;


    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @OpenMethod(
            key = "find.supervisionRecord.by.id",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET
    )
    public SupervisionRecords findById(Long id){
        Response<SupervisionRecords> response = supervisionRecordsReadService.finById(id);
        if (!response.isSuccess()){
            log.error("failed to find supervision reocrd by id = {}, cause : {}",id,response.getError());
            throw new OPServerException(response.getError());
        }
        return response.getResult();
    }

    /**
     * 分页查找全部督查记录
     * @param pageNo
     * @param pageSize
     * @return
     */
    @OpenMethod(
            key = "find.supervisionRecordList",
            paramNames = {"pageNo","pageSize"},
            httpMethods = RequestMethod.GET
    )
    public Paging<SupervisionRecords> findByAll(Integer pageNo,Integer pageSize){
        Response<Paging<SupervisionRecords>> response = supervisionRecordsReadService.findByAll(pageNo,pageSize);
        if (!response.isSuccess()){
            log.error("failed to find supervisionRecordList,cause:{}",response.getError());
            throw new OPServerException(response.getError());
        }
        return response.getResult();
    }

    /**
     * 根据状态(status)分页查询督查记录
     * 1,政府端登录人: 根据当前登录人管理的养殖场 显示这些养殖场中的所有督查记录.
     * 2,养殖端登录人: 拿到当前登录人所在的养殖场ID, 根据此id查询相关的督查记录.
     *
     * @param pageNo
     * @param pageSize
     * @param status
     * @return
     */
    @OpenMethod(
            key = "find.supervisionRecord.by.status",
            paramNames = {"pageNo","pageSize","status"},
            httpMethods = RequestMethod.GET
    )
    public Paging<SupervisionRecords> findByStatus(Integer pageNo,Integer pageSize,Integer status){
        Response<Paging<SupervisionRecords>> response = supervisionRecordsReadService.findByStatus(pageNo,pageSize,status);

        if (!response.isSuccess()){
            log.error("failed to find supervisionReocrdList by status = {},cause:{}",status,response.getError());
            throw new OPServerException(response.getError());
        }
        return response.getResult();
    }

    /**
     * 创建一条督查记录
     * @param supervisionRecords
     * @param toStatus 单据状态走向
     * @return  返回的Map集合中key是"xxxxxId"指定对象的id, value是对应的id
     */
    @OpenMethod(
            key = "create.supervisionReocrds",
            paramNames = {"supervisionReocrds","toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Map<String, Object> create(SupervisionRecords supervisionRecords,Integer toStatus){
/*        LoginUser loginUser = UserUtil.getCurrentUser();
        Integer organizationType = loginUser.getOrganizationType();
        if(organizationType == 3){
            Integer code = (Integer) loginUser.getRoles().get("code");
            Integer departmentType = loginUser.getDepartmentType();
            if(code == 3 && departmentType == 3){
                log.error("this user can't do it");
                throw new OPClientException("this user can't do it");
            }
        }*/
        Response<Map<String,Object>> response = supervisionRecordsWriteService.create(supervisionRecords,toStatus);
        if (!response.isSuccess()){
            log.error("failed.to.create.supervisionRecords.by.supervisionRecords = {}, cause:{}",supervisionRecords,response.getError());
            throw new OPServerException(response.getError());
        }
        return response.getResult();
    }

    /**
     * 更新一条督查记录
     *
     * @param supervisionRecords
     * @param toStatus 状态走向
     * @return 返回的Map为是否更新成功,和更新的ID
     */
    @OpenMethod(
            key = "update.supervisionReocrds",
            paramNames = {"supervisionReocrds","toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Map<String, Object> update(SupervisionRecords supervisionRecords,Integer toStatus){
 /*       LoginUser loginUser = UserUtil.getCurrentUser();
        Integer organizationType = loginUser.getOrganizationType();
        if(organizationType == 3){
            if(!supervisionRecords.getUserId().equals(loginUser.getId())){
                log.error("this user can not handle this report");
                throw new OPClientException("this user can not handle this report");
            }
            Integer code = (Integer) loginUser.getRoles().get("code");
            Integer departmentType = loginUser.getDepartmentType();
            if(code == 3 && departmentType == 3){
                throw new OPClientException("this user can't do it");
            }
        }*/
        Response<Map<String,Object>> response = supervisionRecordsWriteService.update(supervisionRecords,toStatus);
        if (!response.isSuccess()){
            log.error("failed to update supervisionRecords = {}, cause : {}",supervisionRecords,response.getError());
            throw new OPServerException(response.getError());
        }
        return response.getResult();
    }

    /**
     * 不分页,     根据当前登录人管辖养殖场查询督查记录, 根据养殖场去重, 用来在地图上显示.
     * (同时支持按照userId查询和全部查询,如果userId为null或-1不参与)
     *
     * @param status 单据状态状态
     * @param userId 督查人id
     * @return Paging<SupervisionRecords>
     */
    @OpenMethod(
            key = "find.supervisionRecordsDtoList.by.status.userId",
            paramNames = {"status","userId"},
            httpMethods = RequestMethod.GET
    )
    public List<SupervisionRecordsDto> findByMonth(Integer status, Long userId){
        LoginUser loginUser = UserUtil.getCurrentUser();
        List<Long> breedFactoryIds = loginUser.getBreedFactoryIds();//当前登录人所管辖的养殖场id的list
        if (userId  == -1){
            userId = null;
        }
        List<SupervisionRecords> supervisionRecordsList = null;
        Response<List<SupervisionRecords>> response = supervisionRecordsReadService.findByMonthUserId(status,userId,breedFactoryIds);
        if (!response.isSuccess()) {
            log.error("failed to find supervisionReocrdList by status = {} and userId = {},  cause:{}", status,userId, response.getError());
            throw new OPServerException(response.getError());
        }
        supervisionRecordsList = response.getResult();

        //根据supervisionRecordsList 养殖场list 查询出来每个养殖场上的督查轨迹,包括: 有多少条督查轨迹+前三条督查轨迹,
        List<SupervisionRecordsDto> supervisionRecordsDtoList = new ArrayList<>();
        for (int i=0;i<supervisionRecordsList.size();i++){
            SupervisionRecords supervisionRecords = supervisionRecordsList.get(i);//拿到第一条轨迹
            SupervisionRecordsDto supervisionRecordsDto = new SupervisionRecordsDto();
            supervisionRecordsDto.setSupervisionRecords(supervisionRecords);
            Long breedFactoryId = supervisionRecords.getBreedFactoryId();//拿到第一条养殖场id

            //根据养殖场Id  查询督查轨迹.
            //根据养殖场ID查询轨迹,时间倒序排列
            Response<List<SupervisionRecords>> recordsResponse = supervisionRecordsReadService.findByMonthBreedId(status,breedFactoryId,userId);
            supervisionRecordsDto.setArrayList(recordsResponse.getResult());
            supervisionRecordsDtoList.add(supervisionRecordsDto);
        }
        return Response.ok(supervisionRecordsDtoList).getResult();
    }

    /**
     * 分页  不去重        用来点击地图上的点,显示详情
     * 根据养殖场id查询存在这个养殖场上的督查轨迹,并且是当月的.
     *(同时支持按照breedFactoryId查询和全部查询,如果breedFactoryId不为null参与查询,为null不参与,当不需要userId和breedFactoryId参入查询时,给其传入-1)
     *
     * @param pageNo
     * @param pageSize
     * @param status
     * @param breedFactoryId 养殖场ID
     * @param userId 督查人ID
     * @return Paging<SupervisionRecords>
     */
    @OpenMethod(
            key = "paging.supervision.record.by.month",
            paramNames = {"pageNo","pageSize","status","breedFactoryId","userId"},
            httpMethods = RequestMethod.GET
    )
    public Paging<SupervisionRecords> pagingByMonth(Integer pageNo, Integer pageSize, Integer status,Long breedFactoryId,Long userId){
        //如果给了当前登录人userId 就查看当前登录人做的记录, 如果不传就查看这个养殖场下的所有督查记录 不讲是协检员还是官方兽医都是能看到全部的.
        if (breedFactoryId == -1){
            breedFactoryId = null;
        }
        if (userId == -1){
            userId = null;
        }
        Response<Paging<SupervisionRecords>> response = supervisionRecordsReadService.findByMonthBreedNameUserId(pageNo, pageSize, status, breedFactoryId,userId);
            if (!response.isSuccess()){
                log.error("failed to find supervisionReocrd by status = {} and breedFactoryId = {} and userId={},cause:{}", status,breedFactoryId,userId, response.getError());
                throw new OPServerException(response.getError());
            }
            return response.getResult();
    }

}
